import DescriptionList from '@/components/DescriptionList/index';
import IPDADetailModal from '@/components/ipda/ipdaDetailModal';
import SIMDetailModal from '@/components/simCard/simCardDetailModal';
import TboxDetailModal from '@/components/Tbox/tboxDetailModel';
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import { getDicByKey } from '@/support/common';
import { Button, Card, message, Table } from 'antd';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import Ellipsis from '../../../../components/Ellipsis';
import VehicleDetailModal from '../../baseUserProfile/vinDetailModal';
import VehicleBindingModel from './vehicleBindingModel';

const { Description } = DescriptionList;

@connect(state => ({
  baseUser: state.baseUser,
}))
export default class BasicProfile extends Component {
  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.array,
  };
  state = {
    baseUserDetailData: {},
    vehicleDetailData: [],
    userAccountSid: '',
    tboxDetailVisible: false,
    simDetailVisible: false,
    ipdaDetailVisible: false,
    vinDetailVisible: false,
    vinDetailModelData: {},
    tboxDetailModelData: {},
    simDetailModelData: {},
    ipdaDetailModelData: {},
    query: {},
  };
  componentWillMount() {
    if (this.props.location.flag) {
      const { record, data } = this.props.location.state;
      this.setState({ userAccountSid: record.userAccountSid });
      data.sort((a, b) => b.relationshipType - a.relationshipType);
      var hash = {};
      var dataUnique = data.reduce(function(item, next) {
        hash[next.vin] ? '' : (hash[next.vin] = true && item.push(next));
        return item;
      }, []);
      this.setState({ vehicleDetailData: dataUnique });
      this.setState({
        query: this.props.location.state.obj,
      });
    }
  }
  componentDidMount() {
    const { dispatch } = this.props;
    if (this.props.location.flag) {
      const { record } = this.props.location.state;
      dispatch({
        type: 'baseUser/fetchBaseUserBySid',
        payload: record.sid,
        callback: data => {
          this.setState({ baseUserDetailData: data.data });
        },
      });
    }
  }
  handleBindingDate = () => {
    this.refs.VehicleBindingRef.showModel(this.state.userAccountSid);
  };
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.state.formValues = {};
    dispatch({
      type: 'baseUser/fetch',
    });
  };
  handleDetailTbox = deviceId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'tbox/fetchtboxdetail',
      payload: deviceId,
      callback: tboxDetail => {
        if (tboxDetail.statusCode === '0') {
          this.setState({ tboxDetailModelData: tboxDetail.data, tboxDetailVisible: true });
        } else {
          message.error(tboxDetail.statusMessage);
        }
      },
    });
  };
  handleDetailSIM = deviceId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'simCard/findById',
      payload: deviceId,
      callback: simDetail => {
        if (simDetail.statusCode === '0') {
          this.setState({ simDetailModelData: simDetail.data, simDetailVisible: true });
        } else {
          message.error(simDetail.statusMessage);
        }
      },
    });
  };
  handleDetailIPDA = deviceId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'ipda/findById',
      payload: deviceId,
      callback: ipdaDetail => {
        if (ipdaDetail.statusCode === '0') {
          this.setState({ ipdaDetailModelData: ipdaDetail.data, ipdaDetailVisible: true });
        } else {
          message.error(ipdaDetail.statusMessage);
        }
      },
    });
  };
  handleDetailVIN = vin => {
    const { dispatch } = this.props;
    dispatch({
      type: 'basedata/findVehicleProfile',
      payload: vin,
      callback: response => {
        if (response.statusCode === '0') {
          this.setState({ vinDetailModelData: response.data, vinDetailVisible: true });
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };
  unbind = accountBindSid => {
    const { dispatch } = this.props;
    dispatch({
      type: 'baseUser/unbind',
      payload: { accountBindSid },
      callback: data => {
        if (data.code === '200') {
          message.success('解绑成功');
        } else {
          message.error(data.statusMessage, 3);
        }
      },
    }).then(() => {
      dispatch({
        type: 'baseUser/fetchVehicleByUserAccountSid',
        payload: this.state.userAccountSid,
        callback: data => {
          this.setState({ vehicleDetailData: data });
        },
      });
    });
  };
  goBack = () => {
    const { query } = this.state;
    const { dispatch } = this.props;
    dispatch(routerRedux.push({ pathname: '/baseUserManager/baseUser', state: { query } }));
  };

  render() {
    const isAuth = this.context.permissions.includes('/baseUserManager/baseUser/baseUser-opt');
    const tboxAuth = true; //this.context.permissions.includes('/deviceManager/tbox');
    const ipdaAuth = true; //this.context.permissions.includes('/deviceManager/ipda');
    const simCardAuth = true; //this.context.permissions.includes('/deviceManager/simCard');
    if (this.props.location.flag) {
      const { baseUserDetailData } = this.state;
      const status = ['', '已销售', '车厂', '销售取消', '经销商'];
      const type = ['非车主', '车主'];
      const columns = [
        {
          title: 'VIN号',
          dataIndex: 'vin',
          render: text => {
            return <a onClick={() => this.handleDetailVIN(text)}>{text}</a>;
          },
        },
        {
          title: '车联网类型',
          dataIndex: 'projectId',
          render: (text, record) => {
            if (record && record.projectId && record.projectId === 'dfspt') {
              return '手机';
            } else {
              return '传统';
            }
          },
        },
        {
          title: '品牌',
          dataIndex: 'brandId',
          render: val => getDicByKey(this.context.dicData, 'optBrand', val),
        },
        {
          title: '车系',
          dataIndex: 'seriesId',
          render: val => getDicByKey(this.context.dicData, 'vehicleSeries', val),
        },
        {
          title: '车型',
          dataIndex: 'styleId',
          render: val => getDicByKey(this.context.dicData, 'vehicleType', val),
        },
        {
          title: '车辆状态',
          dataIndex: 'status',
          render: val => status[val],
        },
        {
          title: 'SIM卡',
          dataIndex: 'sim',
          render: text => {
            return simCardAuth ? <a onClick={() => this.handleDetailSIM(text)}>{text}</a> : text;
          },
        },
        {
          title: 'T-BOX',
          dataIndex: 'tbox',
          render: text => {
            return tboxAuth ? <a onClick={() => this.handleDetailTbox(text)}>{text}</a> : text;
          },
        },
        {
          title: 'IPDA',
          dataIndex: 'ipda',
          render: text => {
            return ipdaAuth ? <a onClick={() => this.handleDetailIPDA(text)}>{text}</a> : text;
          },
        },
        {
          title: '与用户关系',
          dataIndex: 'relationshipType',
          render: val => type[val],
          // }, {
          //   title: '操作',
          //   dataIndex: '操作',
          //   width: 100,
          //   fixed: 'right',
          //   render: (text, record) => {
          //     return <Popconfirm title="确定要解绑该车辆吗?" onConfirm={() => this.unbind.bind(this)(record.accountBindSid)}>{isAuth ? <a>解绑</a> : ''}</Popconfirm>;
          //   },
        },
      ];
      return (
        <PageHeaderLayout>
          <Card bordered={false} type="inner" title="用户信息">
            <DescriptionList>
              <Description term="用&nbsp;&nbsp;户&nbsp;&nbsp;名" style={{ width: '50%' }}>
                <Ellipsis length={10} tooltip>
                  {baseUserDetailData.userName}
                </Ellipsis>
              </Description>
              <Description term="性&nbsp;&nbsp;&nbsp;&nbsp;别" style={{ width: '50%' }}>
                {getDicByKey(this.context.dicData, `sex`, baseUserDetailData.sexuality + '')}
              </Description>
              <Description term="证件类型" style={{ width: '50%' }}>
                {getDicByKey(this.context.dicData, `certType`, baseUserDetailData.idType + '')}
              </Description>
              <Description term="证件号" style={{ width: '50%' }}>
                <Ellipsis length={18} tooltip>
                  {baseUserDetailData.idNo}
                </Ellipsis>
              </Description>
              <Description term="手&nbsp;&nbsp;机&nbsp;&nbsp;号" style={{ width: '50%' }}>
                {baseUserDetailData.mobilePhone}
              </Description>
              <Description term="邮&nbsp;&nbsp;&nbsp;&nbsp;箱" style={{ width: '50%' }}>
                {baseUserDetailData.email}
              </Description>
              <Description term="紧急联系人" style={{ width: '50%' }}>
                {baseUserDetailData.contract}
              </Description>
              <Description term="紧急联系人电话" style={{ width: '50%' }}>
                {baseUserDetailData.contractPhone}
              </Description>
            </DescriptionList>
          </Card>
          <br />
          {/*<div>*/}
          {/*{isAuth ? <Button icon="plus" type="primary" onClick={this.handleBindingDate}>绑定车辆</Button> : ''}*/}
          {/*</div>*/}
          <br />
          <Card bordered={false} type="inner" title="车辆信息">
            <Table
              rowKey={record => record.vin}
              // loading={loading}
              dataSource={this.state.vehicleDetailData}
              columns={columns}
              pagination={false}
              scroll={{ x: 1400 }}
            />
          </Card>
          <VehicleDetailModal
            changeVisible={() => this.setState({ vinDetailVisible: false, vinDetailModelData: {} })}
            visible={this.state.vinDetailVisible}
            detailModelData={this.state.vinDetailModelData}
            dispatch={this.props.dispatch}
          />
          <TboxDetailModal
            changeVisible={() =>
              this.setState({ tboxDetailVisible: false, tboxDetailModelData: {} })
            }
            visible={this.state.tboxDetailVisible}
            detailModelData={this.state.tboxDetailModelData}
            dispatch={this.props.dispatch}
          />
          <SIMDetailModal
            changeVisible={() => this.setState({ simDetailVisible: false, simDetailModelData: {} })}
            visible={this.state.simDetailVisible}
            detailModelData={this.state.simDetailModelData}
            dispatch={this.props.dispatch}
          />
          <IPDADetailModal
            changeVisible={() =>
              this.setState({ ipdaDetailVisible: false, ipdaDetailModelData: {} })
            }
            visible={this.state.ipdaDetailVisible}
            detailModelData={this.state.ipdaDetailModelData}
            dispatch={this.props.dispatch}
          />
          <VehicleBindingModel
            ref="VehicleBindingRef"
            icon="plus"
            type="primary"
            dispatch={this.props.dispatch}
            userAccountSid={this.state.userAccountSid}
            setVehicle={data => this.setState({ vehicleDetailData: data })}
          />
          <div align="center" width="100%" height="100%">
            <Button key="back" type="primary" size="default" onClick={() => this.goBack()}>
              返回
            </Button>
          </div>
        </PageHeaderLayout>
      );
    } else {
      return (
        <div align="center" width="100%" height="100%">
          <h2>未选择任何用户</h2>
          <Button
            key="back"
            type="primary"
            size="default"
            onClick={e => this.props.history.goBack()}
          >
            返回
          </Button>
        </div>
      );
    }
  }
}
